package com.huawei.admins.platform.gateway.core.server.reactor;

import reactor.core.publisher.Mono;
import reactor.netty.DisposableServer;
import reactor.netty.http.HttpProtocol;
import reactor.netty.http.server.HttpServer;

public class ReactorNettyHttpServer {

    public static void main(String[] args) {

        DisposableServer server = HttpServer.create()
                // 指定支持的协议：HTTP/1.1 和 HTTP/2
                .protocol(HttpProtocol.HTTP11, HttpProtocol.H2)
                // 配置端口
                .port(8080)
                // 处理请求
                .handle((request, response) -> {
                    // 获取请求方法、URI和协议
                    String method = request.method().name();
                    String uri = request.uri();
                    String protocol = request.protocol();

                    // 打印请求信息
                    System.out.println("Received " + method + " request for " + uri + " via " + protocol);

                    // 打印所有请求头
                    System.out.println("Headers:");
                    request.requestHeaders().forEach(entry ->
                            System.out.println(entry.getKey() + ": " + entry.getValue()));

                    // 构建响应
                    String responseBody = String.format(
                            "Method: %s\nURI: %s\nProtocol: %s\n",
                            method, uri, protocol);

                    // 发送响应
                    return response
                            .header("Content-Type", "text/plain")
                            .sendString(Mono.just(responseBody));
                })
                // 绑定并启动服务器
                .bindNow();

        System.out.println("Server started on port " + server.port());

        // 添加关闭钩子
        server.onDispose()
                .block();
    }
}